package cn.cutie.clotconfig.server;

import cn.cutie.clotconfig.server.dal.ConfigsMapper;
import cn.cutie.clotconfig.server.model.Configs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: config server endpoint
 * @Author: Cutie
 * @CreateDate: 2024/4/27 20:18
 * @Version: 0.0.1
 */
@RestController
public class ClotConfigController {
    @Autowired
    ConfigsMapper configsMapper;

    Map<String, Long> VERSIONS = new HashMap<>();

    @Autowired
    DistributedLocks distributedLocks;

    @GetMapping("/list")
   public List<Configs> list(String app, String env, String ns) {
        return configsMapper.list(app, env, ns);
   }

    @PostMapping("/update")
    public List<Configs> update(@RequestParam("app") String app,
                                @RequestParam("env") String env,
                                @RequestParam("ns") String ns,
                                @RequestBody Map<String, String> params) {
        params.forEach((k, v) -> {
            insertOrUpdate(new Configs(app, env, ns, k, v));
        });
        VERSIONS.put(app + "-" + env + "-"  + ns, System.currentTimeMillis());
        return configsMapper.list(app, env, ns);
    }

    private void insertOrUpdate(Configs configs) {
        Configs conf = configsMapper.select(configs.getApp(), configs.getEnv(),configs.getNs(),configs.getPkey());
        if (conf == null){
            configsMapper.insert(configs);
        } else {
            configsMapper.update(configs);
        }
    }

    @GetMapping("/version")
    public long version(String app, String env, String ns){
        return VERSIONS.getOrDefault(app + "-" + env + "-"  + ns, -1L);
    }

    @GetMapping("/status")
    public boolean status(){
        return distributedLocks.getLocked().get();
    }

}
